﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Fluffy.Library.Behaviors
{
	public class DoubleClickBehavior : Behavior<Control>
	{
		public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
			"Command", typeof(ICommand), typeof(DoubleClickBehavior), new PropertyMetadata(null));

		public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(
			"CommandParameter", typeof(object), typeof(DoubleClickBehavior), new PropertyMetadata(null));
		
		public ICommand Command
		{
			get { return (ICommand) GetValue(CommandProperty); }
			set { SetValue(CommandProperty, value); }
		}

		public object CommandParameter
		{
			get { return GetValue(CommandParameterProperty); }
			set { SetValue(CommandParameterProperty, value); }
		}

		protected override void OnAttached()
		{
			base.OnAttached();

			AssociatedObject.MouseDoubleClick += OnMouseDoubleClick;
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();

			AssociatedObject.MouseDoubleClick -= OnMouseDoubleClick;
		}

		private void OnMouseDoubleClick(object sender, MouseEventArgs e)
		{
			if (Command == null)
				return;

			Command.Execute(CommandParameter);
		}
	}
}
